package org.my.spring.agent.common.core.handler;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.my.spring.agent.common.domain.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.Optional;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理HTTP请求方法不支持异常
     * @param e 捕获到的HttpRequestMethodNotSupportedException异常
     * @param request 当前HTTP请求对象
     * @return 包含错误信息的Result对象
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<String> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return getResult(requestURI, e);
    }

    /**
     * 处理未知的运行时异常
     * @param e 捕获到的RuntimeException异常
     * @param request 当前HTTP请求对象
     * @return 包含错误信息的Result对象
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<String> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return getResult(requestURI, e);
    }

    /**
     * 处理通用异常
     * @param e 捕获到的Exception异常
     * @param request 当前HTTP请求对象
     * @return 包含错误信息的Result对象
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        return getResult(requestURI, e);
    }

    /**
     * 处理参数绑定异常
     * @param e 捕获到的BindException异常
     * @return 包含验证错误信息的Result对象
     */
    @ExceptionHandler(BindException.class)
    public Result<String> handleBindException(BindException e) {
        log.error("handleBindException:", e);
        return Result.error(Optional.ofNullable(e.getBindingResult().getFieldError()).map(FieldError::getDefaultMessage).orElse(e.getMessage()));
    }

    /**
     * 处理方法参数验证异常
     * @param e 捕获到的MethodArgumentNotValidException异常
     * @return 包含验证错误信息的Result对象
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException:", e);
        return Result.error(Optional.ofNullable(e.getBindingResult().getFieldError()).map(FieldError::getDefaultMessage).orElse(e.getMessage()));
    }

    /**
     * 异常处理通用方法，抽离重复代码
     * @param requestURI 请求的URI地址
     * @param e 捕获到的异常对象
     * @return 包含错误信息的Result对象
     * @note 特殊处理favicon.ico请求和SQL异常
     */
    private Result<String> getResult(String requestURI, Exception e) {
        if (requestURI.contains("favicon.ico")) {
            return Result.error(requestURI);
        }

        //拦截sql异常
        Throwable rootCause = e.getCause();
        if (rootCause instanceof SQLException) {
            return Result.error(rootCause.getMessage());
        }

        return Result.error(e.getMessage());
    }
}
